#!/usr/bin/env python3
# auto_refresh_global_dashboard.py

import time
import argparse
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By


def find_fullscreen_button(driver):
    """Finds the fullscreen button using exact text match (from your HTML)"""
    # We'll use the most reliable selector: button containing text "Fullscreen"
    selectors = [
        # 1. XPath: Find button containing exact text "Fullscreen"
        '//button[contains(., "Fullscreen")]',
        # 2. CSS: Button with class "ant-btn" (common in Ant Design UIs)
        "button.ant-btn",
        # 3. CSS: Button with text content "Fullscreen"
        'button:contains("Fullscreen")',  # Note: This is XPath in Selenium
    ]

    for selector in selectors:
        try:
            if selector.startswith("//"):
                button = WebDriverWait(driver, 10).until(
                    EC.element_to_be_clickable((By.XPATH, selector))
                )
            else:
                button = WebDriverWait(driver, 10).until(
                    EC.element_to_be_clickable((By.CSS_SELECTOR, selector))
                )
            return button
        except:
            continue
    raise Exception("Fullscreen button not found! Check HTML structure.")


def main():
    # Default values
    DEFAULT_URL = "http://192.168.10.66/camera_monitor"
    DEFAULT_INTERVAL = 600  # 10 minutes

    # Set up argument parser
    parser = argparse.ArgumentParser(description='Automatically refresh and fullscreen a dashboard.')
    parser.add_argument('--url', default=DEFAULT_URL,
                       help=f'URL of the dashboard to refresh (default: {DEFAULT_URL})')
    parser.add_argument('--interval', type=int, default=DEFAULT_INTERVAL,
                       help=f'Refresh interval in seconds (default: {DEFAULT_INTERVAL} seconds)')
    args = parser.parse_args()

    # Set up Chrome options
    chrome_options = Options()
    chrome_options.add_argument("--start-maximized")  # Start maximized
    chrome_options.add_argument("--disable-infobars")
    chrome_options.add_argument("--no-first-run")
    chrome_options.add_argument("--disable-extensions")
    chrome_options.add_argument("--no-sandbox")
    chrome_options.add_argument("--disable-dev-shutdown")
    chrome_options.add_experimental_option("excludeSwitches", ["enable-automation"])
    # chrome_options.add_argument("--headless=new")

    # Initialize driver
    driver = webdriver.Chrome(options=chrome_options)

    try:
        # Main refresh loop
        while True:
            print(f"\nRefreshing at {time.strftime('%H:%M:%S')}")

            # Refresh page
            driver.get(args.url)
            print(f"Page refreshed (URL: {args.url})")
            time.sleep(6)

            # fullscreen
            driver.fullscreen_window()
            time.sleep(3)

            # Re-click fullscreen button
            fullscreen_button = find_fullscreen_button(driver)
            fullscreen_button.click()
            print("Fullscreen")

            # Wait for specified interval
            print(f"Waiting {args.interval} seconds or ({args.interval/60:.1f} minutes)...")
            time.sleep(args.interval)

    except KeyboardInterrupt:
        print("\nStopping script...")
    except Exception as e:
        print(f"\nERROR: {str(e)}")
        driver.quit()
    finally:
        driver.quit()


if __name__ == "__main__":
    main()
